package com.wbp.cms.core.dao;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import com.wbp.cms.client.common.Page;

// @Repository("baseDao")
public class BaseDao {

	private static final Logger logger =Logger.getLogger(BaseDao.class) ;
	@Resource
    private SqlSessionTemplate sqlSessionTemplate;
    
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate)
    {
        this.sqlSessionTemplate = sqlSessionTemplate;
        
    }
    
    protected SqlSessionTemplate getSqlSession()
    {
        return sqlSessionTemplate;
    }
    
    protected <T> int insert(String statementName, T entity) {
    	try
    	{
		  return this.getSqlSession().insert(statementName, entity);
    	}catch(Throwable t)
    	{
    		 if (t.getMessage().indexOf("Duplicate entry") != -1) {
    			 logger.error("insert Duplicate entry error:",t);
    			 String  msg = t.getMessage() ;
    			 int start  = msg.indexOf("Duplicate entry") ;
    			 msg = msg.substring(start);
    			 start  = msg.indexOf("#") ;
    			 msg = msg.substring(0,start);
                 throw new RuntimeException(msg);
             }
    		 logger.error("insert error:",t);
    	}
    	
    	return 0 ;
	}
    
    protected   int update(String statementName ) {
		return this.getSqlSession().update(statementName );
	}
    
    protected <T> int update(String statementName, T entity) {
		return this.getSqlSession().update(statementName, entity);
	}
    
    protected <T> int delete(String statementName, T entity) {
		return this.getSqlSession().delete(statementName, entity) ;
	}
    
    protected Object selectOneObject(String statementName, Object parameterObject) {
        return this.getSqlSession().selectOne(statementName, parameterObject);
    }
    
    protected Object selectOneObject(String statementName, Long  id) {
        return this.getSqlSession().selectOne(statementName, id);
    }

    protected <T> List<T> selectList(String statementName, Object parameterObject) {
        return this.getSqlSession().selectList(statementName, parameterObject) ;
    }
    
    /***
     * 分页查询
     * @param statementName
     * @param parameterObject
     * @param <T>
     * @return
     */
    protected <T> List<T> selectList(String statementName, Page  pageParameterObject) {
        return this.getSqlSession().selectList(statementName, pageParameterObject) ;
    }
    
}
